﻿using AvaloniaMVVM.Helpers;
using AvaloniaMVVM.Models;
using SQLite;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace AvaloniaMVVM.Services
{
    public class PoetryStorage : IPoetryStorage
    {
        public const string DbName = "poetrydb.sqlite3";
        public static readonly string PoetryDbPath = PathHelper.GetLocalFilePath(DbName);


        private SQLiteAsyncConnection connection;
        public SQLiteAsyncConnection Connection => connection ?? new SQLiteAsyncConnection(PoetryDbPath);

        /// <summary>
        /// 创建表 
        /// </summary>
        /// <returns></returns>
        public async Task InitializeAsync()
        {
            await Connection.CreateTableAsync<Poetry>();
        }

        /// <summary>
        /// 插入
        /// </summary>
        /// <param name="poetry"></param>
        /// <returns></returns>
        public async Task InsertAsync(Poetry poetry)
        {
            await Connection.InsertAsync(poetry);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="poetry"></param>
        /// <returns></returns>
        public async Task DeleteAsync(Poetry poetry)
        {
            await Connection.DeleteAsync(poetry);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="poetry"></param>
        /// <returns></returns>
        public async Task UpdateAsync(Poetry poetry)
        {
            await Connection.UpdateAsync(poetry);
        }

        /// <summary>
        /// 根据ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Poetry> GetByIdAsync(int id)
        {
            return await Connection.Table<Poetry>().Where(p => p.Id == id).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public async Task<List<Poetry>> GetAllAsync()
        {
            return await Connection.Table<Poetry>().ToListAsync();
        }
    }
}
